import React, { PureComponent } from 'react';
import { Card, message } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';

import { connect } from 'dva';
import _ from 'lodash';
import moment from 'moment';
import router from 'umi/router';
import ProjectsPath from '@/components/ProjectsPath';
import CurrentStage from '../components/CurrentStage';
import PageEmpty from '@/components/PageEmpty';
import PageTop from './components/PageTop';
import { showConfirm } from '@/utils/utils';
import styles from '../../index.less';
import * as api from '@/services/SupplyPlanMgr';
import { BaseTable, utils, TextWithTags } from '@/components/BaseTable';
import HeaderRenderer from '@/components/BaseTable/HeaderRenderer';

@connect(state => ({
  items: state.SupplyPlanItems,
  orgStructure: state.orgStructure,
  versions: state.OperatingPlanVersions.data,
}))
export default class PriceManage extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      emptyMsg: '',
      // versionType: this.props.match.params.category,
      headerHeight: [],
      titleTree: [],
      fixedColumns: [],
      subtractHeight: '210px', // 表格的高度
    };
  }

  async componentDidMount() {
    const { match } = this.props;
    this.getVersions(this.props);
    // if :version！=null 获取items
    // 根据 items获取 searchItems

    if (match.params.version) {
      this.getItems(this.props);
    }
  }

  componentWillReceiveProps(nextProps) {
    this.getTabkeyState(nextProps);
    // match变动
    if (
      this.props.match.params.stage !== nextProps.match.params.stage ||
      this.props.match.params.category !== nextProps.match.params.category
    ) {
      this.getVersions(nextProps);
    }
    if (
      this.props.match.params.version !== nextProps.match.params.version &&
      nextProps.match.params.version
    ) {
      this.getItems(nextProps);
    }
  }

  // 根据高级筛选按钮显示隐藏判断表格的高度
  subtractHeight = expandForm => {
    this.setState({
      subtractHeight: expandForm ? '274px' : '210px',
    });
  };

  /*
   *判断有没有数据
   *如果有数据就显示数据没数据就显示对应的log提示
   */
  getVersions = (props, callBack = false) => {
    const { dispatch, match } = props;
    const params = {
      projectFid: match.params.stage,
      versionType: match.params.category,
    };
    let str = '不存在供货计划版本';
    if (match.params.category === 'dynamic') {
      str =
        '不存在月度动态版供货计划，在完成月度动态版价格和楼栋计划编制并审批通过后，系统将自动生成供货计划。';
    } else if (match.params.category === 'budget') {
      str = '不存在预算版供货计划，请先新建版本。';
    } else if (match.params.category === 'strategy') {
      str =
        '不存在战规版供货计划，在完成战规版价格和楼栋计划编制并审批通过后，系统将自动生成供货计划。';
    } else if (match.params.category === 'investment') {
      str =
        '不存在投资版供货计划，在完成投资版价格和楼栋计划编制并审批通过后，系统将自动生成供货计划。';
    }
    const self = this;
    // 获取versions
    dispatch({
      type: 'OperatingPlanVersions/fetch',
      payload: { params },
      callback: versions => {
        // 如果:version==null
        if (!versions.length) {
          self.setState({ emptyMsg: str });
        }
        //  跳转第一个version
        // if (versions && !match.params.version) {
        if ((versions && versions.length > 0 && !match.params.version) || callBack) {
          router.replace(
            `/OperatingPlan/SupplyPlan/${match.params.level1}/${match.params.level2}/${match.params.project}/${match.params.stage}/${match.params.category}/${versions[0].versionId}`,
          );
        }
      },
    });
  };

  /*
   *数据加载中
   */
  getItems = (props, values = '') => {
    this.setState({ emptyMsg: '版本数据加载中...' });
    const self = this;
    const { dispatch, match } = props;
    const params = {
      versionId: match.params.version,
      code: values,
      type: '',
    };
    dispatch({
      type: 'SupplyPlanItems/init',
      payload: {
        params,
      },
      callback: data => {
        self.setState({ emptyMsg: '' });
        if (_.isEmpty(data)) {
          self.setState({ emptyMsg: '版本数据加载失败' });
        }
      },
    });
  };

  getArrayNumbers = (text, division = 1) => {
    if (!_.isEmpty(text) && text.indexOf('/') > -1) {
      // text.split('/')
      const temp = [];
      _.forEach(text.split('/'), value => {
        temp.push((_.trim(value) * 1) / division);
      });
      text = temp;
    } else {
      text = (text * 1) / division;
    }

    return text;
  };

  // 判断 tab  投资、战规、预算、动态 显示对应的头部
  getTabkeyState = props => {
    const { category } = props.match.params;
    if (props.versions && props.versions.length) {
      if (
        category === 'investment' ||
        (category === 'budget' && props.versions[0].versionAttr !== 'after_warplan')
      ) {
        this.setState({
          headerHeight: [30, 60],
          titleTree: [
            {
              name: '分期/组团/供应批次/产品构成',
              key: 'id',
              colspan: 1,
              rowspan: 3,
              frozen: 'left',
            },
            {
              name: '投资版总货值',
              key: 'zhz',
              rowspan: 1,
              colspan: 1 * 4,
            },
            {
              name: '供货日期',
              key: 'supplyTime',
              colspan: 1,
              rowspan: 3,
            },
          ],
          fixedColumns: [
            {
              key: 'name',
              dataKey: 'name',
              width: 260,
              frozen: 'left',
              dataGetter: ({ rowData }) => {
                const text = rowData.name;
                const result = { text };
                result.textFirst = true;
                if (rowData.isSupply === 0) {
                  result.tags = [{ text: '未供', color: 'orange', border: true }];
                } else if (rowData.isSupply === 1) {
                  result.tags = [{ text: '已供', color: 'green' }];
                }

                if (rowData.isDelay === 1) {
                  result.tags.unshift({ text: '延迟', color: 'red' });
                }
                return result;
              },
              cellRenderer: <TextWithTags />,
            },
            // 投资版总货值-套数
            {
              key: 'totalNum',
              dataKey: 'totalNum',
              align: 'right',
              width: 200,
              headerRenderer: () => (
                <div>
                  <HeaderRenderer {...this.props} type={1}>
                    <div>套数/车位数</div>
                    <div>(套/个)</div>
                  </HeaderRenderer>
                </div>
              ),
              dataGetter: ({ rowData }) => {
                return utils.calculate.NumberView({
                  cellData: this.getArrayNumbers(rowData.num),
                  precision: 0,
                });
              },
            },
            // 投资版总货值-面积
            {
              key: 'totalSaleArea',
              dataKey: 'totalSaleArea',
              align: 'right',
              width: 200,
              headerRenderer: () => (
                <div>
                  <div>可售面积</div>
                  <div>(平米)</div>
                </div>
              ),
              // dataGetter: ({ rowData }) => {
              //   if (rowData.isParking === 1) {
              //     return '';
              //   }
              //   console.log(rowData.saleArea,'rowData.saleArea')
              //   return utils.calculate.NumberView({
              //     cellData: this.getArrayNumbers(rowData.saleArea),
              //     precision: 2,
              //   });
              // },
              cellRenderer: data => (data.rowData.isParking === 1 ? '' : data.rowData.saleArea),
            },
            // 投资版总货值-均价
            {
              key: 'totalAvgPrice',
              dataKey: 'totalAvgPrice',
              width: 130,
              align: 'right',
              headerRenderer: () => (
                <div>
                  <HeaderRenderer {...this.props} type={2}>
                    <div>均价</div>
                    <div>(元/平米，个)</div>
                  </HeaderRenderer>
                </div>
              ),
              dataGetter: ({ rowData }) => {
                return utils.calculate.NumberView({
                  cellData: this.getArrayNumbers(rowData.avgPrice),
                  precision: 0,
                });
              },
            },
            // 投资版总货值-金额
            {
              key: 'noTotalPrice',
              dataKey: 'totalPrice',
              align: 'right',
              width: 200,
              headerRenderer: () => (
                <div>
                  <HeaderRenderer {...this.props} type={3}>
                    <div>金额</div>
                    <div>(万元：合计/房源/车位)</div>
                  </HeaderRenderer>
                </div>
              ),
              dataGetter: ({ rowData }) => {
                return utils.calculate.NumberView({
                  cellData: this.getArrayNumbers(rowData.price, 10000),
                  precision: 0,
                });
              },
            },
            {
              key: 'supplyTime',
              dataKey: 'supplyTime',
              align: 'center',
              width: 160,
              dataGetter: ({ rowData }) => {
                if (!_.isEmpty(rowData.supplyTime)) {
                  return moment(rowData.supplyTime).format('YYYY-MM-DD');
                }
              },
            },
          ],
        });
      } else {
        this.setState({
          headerHeight: [30, 30, 60],
          titleTree: [
            {
              name: '分期/组团/业态/楼栋',
              key: 'id',
              colspan: 1,
              rowspan: 4,
              frozen: 'left',
            },
            // {
            //   name: '战规版总货值',
            //   key: 'zhz',
            //   rowspan: 2,
            //   colspan: 1 * 5,
            // },
            {
              name: '供货计划与实际',
              key: 'planActual',
              rowspan: 1,
              children: [
                {
                  name: '供货计划',
                  key: 'plan',
                  rowspan: 1,
                  colspan: 1 * 5,
                },
                {
                  name: '供货实际',
                  key: 'actual',
                  rowspan: 1,
                  colspan: 1 * 5,
                },
                {
                  name: '达成率(%)',
                  key: 'achievingRate',
                  rowspan: 2,
                  colspan: 1,
                },
              ],
            },
          ],
          fixedColumns: [
            {
              key: 'name',
              dataKey: 'name',
              width: 260,
              frozen: 'left',
              dataGetter: ({ rowData }) => {
                const text = rowData.name;
                const result = { text };
                result.textFirst = true;
                if (rowData.isSupply === 0) {
                  result.tags = [{ text: '未供', color: 'orange', border: true }];
                } else if (rowData.isSupply === 1) {
                  result.tags = [{ text: '已供', color: 'green' }];
                }
                if (rowData.isDelay === 1) {
                  result.tags.unshift({ text: '延迟', color: 'red' });
                }
                return result;
              },
              cellRenderer: <TextWithTags />,
            },
            // 战规版总货值-套数
            // {
            //   key: 'totalNum',
            //   dataKey: 'totalNum',
            //   align: 'right',
            //   width: 100,
            //   headerRenderer: () => (
            //     <div>
            //       <div>套数/车位数</div>
            //       <div>(套/个)</div>
            //     </div>
            //   ),
            //   cellRenderer: data => data.rowData.num,
            // },
            // // 战规版总货值-面积
            // {
            //   key: 'totalSaleArea',
            //   dataKey: 'totalSaleArea',
            //   align: 'right',
            //   width: 100,
            //   headerRenderer: () => (
            //     <div>
            //       <div>可售面积</div>
            //       <div>(平米)</div>
            //     </div>
            //   ),
            //   cellRenderer: data => data.rowData.saleArea,
            // },
            // // 战规版总货值-均价
            // {
            //   key: 'totalAvgPrice',
            //   dataKey: 'totalAvgPrice',
            //   align: 'right',
            //   width: 100,
            //   headerRenderer: () => (
            //     <div>
            //       <div>均价</div>
            //       <div>(元/平米，个)</div>
            //     </div>
            //   ),
            //   cellRenderer: data => data.rowData.avgPrice,
            // },
            // // 战规版总货值-金额
            // {
            //   key: 'totalPrice',
            //   dataKey: 'totalPrice',
            //   align: 'right',
            //   width: 150,
            //   rowspan: 2,
            //   headerRenderer: () => (
            //     <div>
            //       <div>不含(未推售车位)货值</div>
            //       <div>(万元：合计/房源/车位)</div>
            //     </div>
            //   ),
            //   cellRenderer: data => data.rowData.price,
            // },
            // {
            //   key: 'YestotalPrice',
            //   dataKey: 'totalPrice',
            //   align: 'right',
            //   width: 150,
            //   rowspan: 2,
            //   headerRenderer: () => (
            //     <div>
            //       <div>含(未推售车位)货值</div>
            //       <div>(万元：合计/房源/车位)</div>
            //     </div>
            //   ),
            //   cellRenderer: data => data.rowData.price2,
            // },
            // 供货计划-时间
            {
              key: 'afterWarplanPlanTime',
              dataKey: 'planTime',
              width: 100,
              headerRenderer: () => <div>供货时间</div>,
              dataGetter: ({ rowData }) => {
                if (!_.isEmpty(rowData.supplyTime)) {
                  return moment(rowData.supplyTime).format('YYYY-MM-DD');
                }
              },
            },
            // 供货计划-套数
            {
              key: 'totalNum',
              dataKey: 'totalNum',
              align: 'right',
              width: 100,
              headerRenderer: () => (
                <div>
                  <HeaderRenderer {...this.props} type={1}>
                    <div>套数/车位数</div>
                    <div>(套/个)</div>
                  </HeaderRenderer>
                </div>
              ),
              dataGetter: ({ rowData }) => {
                return utils.calculate.NumberView({
                  cellData: this.getArrayNumbers(rowData.num),
                  precision: 0,
                });
              },
            },
            // 供货计划-面积
            {
              key: 'totalSaleArea',
              dataKey: 'totalSaleArea',
              align: 'right',
              width: 100,
              headerRenderer: () => (
                <div>
                  <div>可售面积</div>
                  <div>(平米)</div>
                </div>
              ),
              // dataGetter: ({ rowData }) => {
              //   if (rowData.isParking === 1) {
              //     return '';
              //   }
              //   console.log(rowData.saleArea, 'rowData.saleArea')
              //   return utils.calculate.NumberView({
              //     cellData: this.getArrayNumbers(rowData.saleArea),
              //     precision: 2,
              //   });
              // },
              cellRenderer: data => (data.rowData.isParking === 1 ? '' : data.rowData.saleArea),
            },
            // 供货计划-均价
            {
              key: 'totalAvgPrice',
              dataKey: 'totalAvgPrice',
              align: 'right',
              width: 130,
              headerRenderer: () => (
                <div>
                  <HeaderRenderer {...this.props} type={2}>
                    <div>均价</div>
                    <div>(元/平米，个)</div>
                  </HeaderRenderer>
                </div>
              ),
              dataGetter: ({ rowData }) => {
                return utils.calculate.NumberView({
                  cellData: this.getArrayNumbers(rowData.avgPrice),
                  precision: 0,
                });
              },
            },
            // 供货计划-金额
            {
              key: 'totalPrice',
              dataKey: 'totalPrice',
              align: 'right',
              width: 200,
              rowspan: 2,
              headerRenderer: () => (
                <div>
                  <HeaderRenderer {...this.props} type={3}>
                    <div>金额</div>
                    <div>(万元：合计/房源/车位)</div>
                  </HeaderRenderer>
                </div>
              ),
              dataGetter: ({ rowData }) => {
                return utils.calculate.NumberView({
                  cellData: this.getArrayNumbers(rowData.price, 10000),
                  precision: 0,
                });
              },
            },
            // 实际供货-时间
            {
              key: 'planTime',
              dataKey: 'planTime',
              align: 'left',
              width: 100,
              headerRenderer: () => <div>供货时间</div>,
              dataGetter: ({ rowData }) => {
                if (!_.isEmpty(rowData.actualSupplyDate)) {
                  return moment(rowData.actualSupplyDate).format('YYYY-MM-DD');
                }
              },
            },
            // 供货实际-套数
            {
              key: 'actualNum',
              dataKey: 'actualNum',
              align: 'right',
              width: 100,
              dataGetter: ({ rowData }) => {
                return utils.calculate.NumberView({
                  cellData: this.getArrayNumbers(rowData.actualNum),
                  precision: 0,
                });
              },
              headerRenderer: () => (
                <div>
                  <HeaderRenderer {...this.props} type={1}>
                    <div>套数/车位数</div>
                    <div>(套/个)</div>
                  </HeaderRenderer>
                </div>
              ),
            },
            // 供货实际-面积
            {
              key: 'actualArea',
              dataKey: 'actualArea',
              align: 'right',
              width: 100,
              // dataGetter: ({ rowData }) => {
              //   if (rowData.isParking === 1) {
              //     return '';
              //   }
              //   return utils.calculate.NumberView({
              //     cellData: this.getArrayNumbers(rowData.actualArea),
              //     precision: 2,
              //   });
              // },
              cellRenderer: data => (data.rowData.isParking === 1 ? '' : data.rowData.actualArea),
              headerRenderer: () => (
                <div>
                  <div>可售面积</div>
                  <div>(平米)</div>
                </div>
              ),
            },
            // 供货实际-均价
            {
              key: 'actualAveragePrice',
              dataKey: 'actualAveragePrice',
              align: 'right',
              width: 130,
              dataGetter: ({ rowData }) => {
                return utils.calculate.NumberView({
                  cellData: this.getArrayNumbers(rowData.actualAveragePrice),
                  precision: 0,
                });
              },
              headerRenderer: () => (
                <div>
                  <HeaderRenderer {...this.props} type={2}>
                    <div>均价</div>
                    <div>(元/平米，个)</div>
                  </HeaderRenderer>
                </div>
              ),
            },
            // 供货实际-金额
            {
              key: 'NoActualPrice',
              dataKey: 'NoActualPrice',
              align: 'right',
              width: 180,
              dataGetter: ({ rowData }) => {
                return utils.calculate.NumberView({
                  cellData: this.getArrayNumbers(rowData.actualPrice, 10000),
                  precision: 0,
                });
              },
              headerRenderer: () => (
                <div>
                  <HeaderRenderer {...this.props} type={3}>
                    <div>金额</div>
                    <div>(万元：合计/房源/车位)</div>
                  </HeaderRenderer>
                </div>
              ),
            },
            // 供货计划与实际-达成率
            {
              key: 'achievingRate',
              dataKey: 'achievingRate',
              align: 'right',
              width: 100,
              cellRenderer: data => {
                const { achievingRate } = data.rowData;
                if (achievingRate === 'null' || _.isNull(achievingRate)) {
                  return '';
                }
                if (achievingRate) {
                  if (achievingRate === '-') {
                    return '-';
                  }
                  return `${_.round(data.rowData.achievingRate * 1 * 100, 1).toFixed(3)}%`;
                }
              },
              // (data.rowData.achievingRate === 'null'
              //   ? '0%'
              //   : _.round(data.rowData.achievingRate * 1 * 100, 1) + '%'),
            },
          ],
        });
      }
    }
  };

  // 创建版本  手动创建供货计划预算版新版本需要分期 ----id  projectFid
  handleCreateEdition = projectFid => {
    // const { match } = this.props;
    api.createSupplyBudgetVersionUsingPOST({ params: { projectFid } }).then(data => {
      if (data.code === 1) {
        message.success('创建版本成功');
        // if (match.params.version) {
        //   this.getItems(this.props);
        // }
        this.getVersions(this.props, true);
      }
    });
    // _paq.push(['trackEvent', 'appClick', '<appName>','点击应用' ]);
  };

  /**
   * @description:  供货版本对比
   * @param {type}
   * @return
   */
  handleVersionComparisonClick = () => {
    // _paq.push(['trackEvent', 'appClick', '<appName>','点击应用' ]);
  };

  // 供货计划重新打考核标签 -- Begin
  setVersionAssessment = params => {
    showConfirm(
      () => {
        api
          .setAssessmentTagUsingPUT({
            params: { versionId: params.version, projectFid: params.stage },
          })
          .then(result => {
            if (result && result.code * 1 && result.data === 'ok') {
              message.success(result.message, () => {
                router.replace(
                  `/OperatingPlan/SupplyPlan/${params.level1}/${params.level2}/${params.project}/true/${params.category}/${params.version}`,
                );
                router.replace(
                  `/OperatingPlan/SupplyPlan/${params.level1}/${params.level2}/${params.project}/${params.stage}/${params.category}/${params.version}`,
                );
              });
            }
          });
      },
      '设置考核版',
      '确定将此版本设为考核版吗？',
    );
  };
  // 供货计划重新打考核标签 -- End

  render() {
    const { fixedColumns, headerHeight, titleTree, subtractHeight } = this.state;
    const treeData = this.props.items.searched;
    const { expandedRowKeys } = this.props.items;
    const { versions } = this.props;
    const { category } = this.props.match.params;
    let rowLength = 2;
    if (versions && versions.length) {
      rowLength =
        category === 'investment' ||
        (category === 'budget' &&
          versions.length > 0 &&
          versions[0].versionAttr !== 'after_warplan')
          ? 1
          : 2;
    }
    const headerRenderer = utils.getHeaderRenderer(titleTree, rowLength);
    return (
      <PageHeaderWrapper
        className="page-header"
        breadcrumb={null}
        title={<ProjectsPath menu="SupplyPlan" {...this.props} />}
        tags={<CurrentStage {...this.props} />}
      >
        <Card className="page-header-card">
          <div className={styles.container}>
            <PageTop
              {...this.props}
              handleCreateEdition={this.handleCreateEdition}
              setVersionAssessment={this.setVersionAssessment}
              getItems={this.getItems}
              treeData={treeData}
              expandForm={this.subtractHeight}
            />
            {this.props.match.params.version && versions.length && treeData.length > 0 ? (
              <BaseTable
                subtractHeight={subtractHeight}
                defaultExpandedRowKeys={expandedRowKeys}
                expandColumnKey="name"
                fixedColumns={fixedColumns}
                headerHeight={headerHeight}
                headerRenderer={headerRenderer}
                treeData={treeData}
              />
            ) : (
              <PageEmpty emptyTitle={this.state.emptyMsg} />
            )}
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}
